using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using pal.SvnConf.Core;

namespace pal.SvnConf.GUI
{
    public class GroupsDataSetView : DataSet, IBindingSource
    {
        public const string GROUPS_DATATABLE_NAME = "Groups";
        public const string GROUPNAME_COLUMN = "Group";
        public const string GROUP_MEMBERS_COLUMN = "Members";

        private readonly List<Group> _groups;
        private DataTable _groupsTable;

        public GroupsDataSetView(List<Group> groups)
        {
            _groups = groups;
            initializeTable();
            setData();
        }

        public BindingSource BindingSource
        {
            get { return new BindingSource(this, GROUPS_DATATABLE_NAME); }
        }

        private void setData()
        {
            foreach (Group group in _groups)
                _groupsTable.Rows.Add(getRowDataFor(group));
        }

        private static object[] getRowDataFor(Group group)
        {
            string[] members = new string[group.Members.Count];
            for (int i = 0; i < group.Members.Count; i++)
                members[i] = group.Members[i].ConfigurationUsageName;

            return new object[] {group.Name, string.Join(", ", members)};
        }

        private void initializeTable()
        {
            _groupsTable = new DataTable(GROUPS_DATATABLE_NAME);
            setSchema();
            Tables.Add(_groupsTable);
        }

        private void setSchema()
        {
            _groupsTable.Columns.Add(GROUPNAME_COLUMN);
            _groupsTable.Columns.Add(GROUP_MEMBERS_COLUMN);
        }
    }
}